package com.navinfo.tripanalysis.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.navinfo.tripanalysis.pojo.StatusAddition;
import org.apache.spark.sql.Row;
import scala.collection.mutable.WrappedArray;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 附加状态位的工具类
 */
public class StatusAdditionUtils {

    public static List<StatusAddition> parseToList(String statuslist) {
        if (statuslist == null) {
            return Collections.emptyList();
        }
        TypeReference<List<String>> typeReference = new TypeReference<List<String>>() {};
        List<String> dataList = JSON.parseObject(statuslist, typeReference);
        List<StatusAddition> statusList = new ArrayList<>();
        for (String data : dataList) {
            statusList.add(parseString(data));
        }
        return statusList;
    }

    public static List<StatusAddition> parseRow(Row structRow) {
        if (structRow == null) {
            return Collections.emptyList();
        }
        List<StatusAddition> statusList = new ArrayList<>();
        WrappedArray.ofRef array = structRow.getAs("status");
        if (array == null) {
            return Collections.emptyList();
        }
        scala.collection.Iterator<Row> itor = array.iterator();
        while (itor.hasNext()) {
            Row row = itor.next();
            statusList.add(new StatusAddition(getValue(row.getAs("types"), 0), getValue(row.getAs("statusvalue"), 0)));
        }
        return statusList;
    }

    private static StatusAddition parseString(String obj) {
        String[] arr = obj.split("_");
        return new StatusAddition(arr[0], Long.parseLong(arr[1]));
    }

    private static <T> T getValue(Object o, Object defaultValue) {
        if (o == null) {
            return (T) defaultValue;
        }
        return (T) o;
    }
}
